package com.rt.easyjava.base.biz1.controller.app;

import com.rt.easyjava.base.biz1.bean.TmptBaseFileBiz;
import com.rt.easyjava.base.biz1.dto.DfsFileDto;
import com.rt.easyjava.base.biz1.service.intf.TmptBaseFileBizService;
import com.rt.easyjava.base.utils.DfsService;
import com.rt.easyjava.base.utils.ImgUtil;
import com.rt.easyjava.common.base.Result;
import com.rt.easyjava.common.exception.ControllerException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: jxl
 * @Date: 2020/06/18
 * @Time: 15:22
 */
@RestController
@RequestMapping("/fdfsauth")
@Api(value = "/fdfsauth", tags = "FastDfsUploadAuthController -  IMG上传")
@Slf4j
public class FastDfsUploadAuthController extends ControllerException {

    @Resource
    protected TmptBaseFileBizService tmptBaseFileBizService;

    @Resource
    private DfsService dfsService;

    @Value("${fdfs.uri}")
    private String urlPrefix;

    @Value("${fdfs.tokens}")
    private String tokens;

    @PreAuthorize("hasAuthority('fdfs:upload')")
    @PostMapping(value = "/uploadBase64")
    @ApiOperation("Base64图片上传")
    public Result uploadImgBase64(@RequestBody String fileBase64, String userDetailsJson) throws Exception {
        TmptBaseFileBiz tmptBaseFileBiz = new TmptBaseFileBiz();
        tmptBaseFileBiz.setUserDetailsJson(userDetailsJson);
        tmptBaseFileBiz.setTmptBaseFileBizService(tmptBaseFileBizService);
        MultipartFile file = ImgUtil.base64ToMultipart(fileBase64);
        Map<String, Object> map = dfsService.uploadFile(file, tmptBaseFileBiz);
        if (map.get("code").equals("0000")) {
            Map resultMap = new HashMap();
            String filePath = map.get("fileId").toString();
            String downloadUrl = urlPrefix + "/" + filePath;
            resultMap.put("group", filePath);
            resultMap.put("url", downloadUrl);
            return Result.builder(resultMap);
        }
        return Result.builder();
    }

    @PreAuthorize("hasAuthority('fdfs:upload')")
    @PostMapping(value = "/multiUploadEncodedImgBy64")
    @ApiOperation(value = "Base64多图片上传", notes = "基于Base64编码的多文件上传。" +
            "处理过程中多个文件分次上传，因此存在部分成功的情况。返回结果中success为true则表明全部成功，" +
            "false表明为部分成功或者全部失败," +
            "返回结果中会告知具体每个文件的上传结果和下载地址。")
    public Result multiUploadImgBase64(@RequestBody String[] encodedFiles, String userDetailsJson) {
        TmptBaseFileBiz tmptBaseFileBiz = new TmptBaseFileBiz();
        tmptBaseFileBiz.setUserDetailsJson(userDetailsJson);
        tmptBaseFileBiz.setTmptBaseFileBizService(tmptBaseFileBizService);

        List<DfsFileDto> downloadParam = new ArrayList<>();
        if (ObjectUtils.isEmpty(encodedFiles)) {
            return Result.builder().fault("文件上传：参数不能为空！");
        }
        boolean allIsSuccess = true;
        for (int i = 0; i < encodedFiles.length; i++) {
            try {
                MultipartFile file = ImgUtil.base64ToMultipart(encodedFiles[i]);
                Map<String, Object> map = dfsService.uploadFile(file, tmptBaseFileBiz);
                DfsFileDto uploadResult = new DfsFileDto();
                uploadResult.setFileIndex(i);
                boolean success = "0000".equals(map.get("code"));
                allIsSuccess = allIsSuccess && success;
                uploadResult.setSuccess(success);
                if (success) {
                    String filePath = map.get("fileId").toString();
                    String downloadUrl = urlPrefix + "/" + filePath;
                    uploadResult.setGroup(filePath);
                    uploadResult.setUrl(downloadUrl);
                }
                downloadParam.add(uploadResult);
            } catch (Exception e) {
                log.error("文件上传出现异常，参数：{},错误信息:{}", encodedFiles[i], e);
            }

        }
        if (allIsSuccess) {
            return Result.builder().setList(downloadParam).success("请求处理成功！");
        } else {
            return Result.builder().setList(downloadParam).fault("请求未能全部成功，请查看返回明细！");
        }
    }

    @PreAuthorize("hasAuthority('fdfs:upload')")
    @PostMapping(value = "/uploadInputStream")
    @ApiOperation("InputStream图片上传")
    public Result uploadImgInputStream(@RequestBody InputStream inputStream, String userDetailsJson) throws Exception {
        TmptBaseFileBiz tmptBaseFileBiz = new TmptBaseFileBiz();
        tmptBaseFileBiz.setUserDetailsJson(userDetailsJson);
        tmptBaseFileBiz.setTmptBaseFileBizService(tmptBaseFileBizService);
        Map<String, Object> map = dfsService.uploadFile(inputStream, tmptBaseFileBiz, "jpg");
        if (map.get("code").equals("0000")) {
            Map resultMap = new HashMap();
            String filePath = map.get("fileId").toString();
            String downloadUrl = urlPrefix + "/" + filePath;
            resultMap.put("group", filePath);
            resultMap.put("url", downloadUrl);
            return Result.builder(resultMap);
        }
        return Result.builder().fault("上传失败！");
    }

    @PreAuthorize("hasAuthority('fdfs:upload')")
    @PostMapping(value = "/uploadMultiFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, headers = "content-type=" + MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation("图片上传")
    public Result uploadImg(MultipartFile file, String userDetailsJson) throws Exception {
        TmptBaseFileBiz tmptBaseFileBiz = new TmptBaseFileBiz();
        tmptBaseFileBiz.setUserDetailsJson(userDetailsJson);
        tmptBaseFileBiz.setTmptBaseFileBizService(tmptBaseFileBizService);
        Map<String, Object> map = dfsService.uploadFile(file, tmptBaseFileBiz);
        if (map.get("code").equals("0000")) {
            Map resultMap = new HashMap();
            String filePath = map.get("fileId").toString();
            String downloadUrl = urlPrefix + "/" + filePath;
            resultMap.put("group", filePath);
            resultMap.put("url", downloadUrl);
            return Result.builder(resultMap);
        }
        return Result.builder();
    }

    @PreAuthorize("hasAuthority('fdfs:upload')")
    @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE, headers = "content-type=" + MediaType.MULTIPART_FORM_DATA_VALUE)
    @ApiOperation("文件上传")
    public Result uploadFile(MultipartFile file, String userDetailsJson) throws Exception {
        TmptBaseFileBiz tmptBaseFileBiz = new TmptBaseFileBiz();
        tmptBaseFileBiz.setUserDetailsJson(userDetailsJson);
        tmptBaseFileBiz.setTmptBaseFileBizService(tmptBaseFileBizService);
        Map<String, Object> map = dfsService.uploadFile(file, tmptBaseFileBiz);
        if (map.get("code").equals("0000")) {
            Map resultMap = new HashMap();
            String filePath = map.get("fileId").toString();
            String downloadUrl = urlPrefix + "/" + filePath;
            resultMap.put("group", filePath);
            resultMap.put("url", downloadUrl);
            return Result.builder(resultMap);
        }
        return Result.builder();
    }

    @PreAuthorize("hasAuthority('fdfs:upload')")
    @PostMapping(value = "/uploadFileBase64")
    @ApiOperation("base64文件上传")
    public Result uploadFile(@RequestBody String fileBase64, String userDetailsJson) throws Exception {
        TmptBaseFileBiz tmptBaseFileBiz = new TmptBaseFileBiz();
        tmptBaseFileBiz.setUserDetailsJson(userDetailsJson);
        tmptBaseFileBiz.setTmptBaseFileBizService(tmptBaseFileBizService);
        MultipartFile file = ImgUtil.base64ToMultipart(fileBase64);
        Map<String, Object> map = dfsService.uploadFile(file, tmptBaseFileBiz);
        if (map.get("code").equals("0000")) {
            Map resultMap = new HashMap();
            String filePath = map.get("fileId").toString();
            String downloadUrl = urlPrefix + "/" + filePath;
            resultMap.put("group", filePath);
            resultMap.put("url", downloadUrl);
            return Result.builder(resultMap);
        }
        return Result.builder();
    }


}
